package com.ysy.mq;


import com.alibaba.fastjson2.JSON;
import com.ysy.constant.RedisConstant;
import com.ysy.constant.RocketMqConstant;
import com.ysy.entity.dto.FollowCancelCountDTO;
import com.ysy.enums.FollowCancelTypeEnum;
import com.ysy.mapper.UserCountMapper;
import com.ysy.persimmons.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * 关注或者取消
 * 默认无需单个消费
 * @author yangSy git地址：git地址：url:<a href="https://gitee.com/ysyGit01/persimmons"/>
 * @date 2025/4/30
 */
@Component
@RocketMQMessageListener(
        consumerGroup ="persimmons_group"+RocketMqConstant.FOLLOW_CANCEL_COUNT_TOPIC,
        topic = RocketMqConstant.FOLLOW_CANCEL_COUNT_TOPIC,messageModel = MessageModel.CLUSTERING)
public class FollowCancelCountConsumer implements RocketMQListener<String> {

    private static Logger log = LoggerFactory.getLogger(FollowCancelCountConsumer.class);

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private UserCountMapper userCountMapper;

    @Override
    public void onMessage(String message) {
        System.out.println("11111111111111111111111");
        log.info("当前mq开始消费");
        // 判断类型是关注还是取消
        if (StringUtils.isBlank(message)) {
            log.warn("当前mq消费数据库为空，暂不处理");
            return;
        }
        FollowCancelCountDTO dto = JSON.parseObject(message, FollowCancelCountDTO.class);

        // 跟新redis,使用hash 还有其他字段
        Long userId = dto.getUserId();
        String userRedisCountKey =  RedisConstant.getUserCountKey(userId);

        Boolean exist = redisTemplate.hasKey(userRedisCountKey);
        if (!exist) {
            log.error("persimmons_count_group_follow_cancel_count_topic,redis中数据不存在暂不处理");
            return;
        }
        FollowCancelTypeEnum followCancelTypeEnum = FollowCancelTypeEnum.get(dto.getType());
        if (Objects.isNull(followCancelTypeEnum)) {
            log.error("persimmons_count_group_follow_cancel_count_topic,未知的类型暂不处理");
            return;
        }
        // 写入redis库
        long count = followCancelTypeEnum == FollowCancelTypeEnum.FOLLOW ? 1:-1;
        redisTemplate.opsForHash().increment(userRedisCountKey, RedisConstant.HASH_FIELD_FOLLOW_TOTAL, count);

        // 写入数据库，如果数据大，可以用异步或者mq去存储db再加限流；
        // mybatis plus自带的没有这样写的效率高，plus需要查询2次
        userCountMapper.updateOrInsertFollowCount(userId,count);

    }
}
